package cn.fz.ssedemo.controller;

import cn.fz.ssedemo.config.SseEmitterService;
import cn.fz.ssedemo.utils.JwtUtils;
import cn.hutool.jwt.JWTPayload;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Slf4j
@RequestMapping("sse")
@RestController
@Tag(name = "sse测试模块",description = "sse测试模块")
@RequiredArgsConstructor
public class SseController {
    private final SseEmitterService sseEmitterService;

    @Operation(summary = "SSE 订阅接口", description = "建立 SSE 长连接，实时接收报警信息")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    @GetMapping("/subscribe")
    public SseEmitter subscribe(@RequestParam("token") String token) {
    // public SseEmitter subscribe(@RequestHeader("Authorization") String token) {
        // 通过 token 获取当前用户 ID（可使用 JWT 解析）
        String userId = parseUserIdFromToken(token);
        // 设置超时时间
        SseEmitter emitter = new SseEmitter(60_000L);
        sseEmitterService.addEmitter(userId, emitter);

        // 超时或异常时移除
        emitter.onCompletion(() -> sseEmitterService.removeEmitter(userId));
        emitter.onTimeout(() -> sseEmitterService.removeEmitter(userId));

        return emitter;
    }

    private String parseUserIdFromToken(String token) {
        JWTPayload jwtPayload = JwtUtils.parseToken(token);
        return jwtPayload.getClaim("id").toString();
    }
}
